﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;

namespace QLThuChi.OtherForms
{
    #region Using
    using QLThuChi.Models;
    using QLThuChi.Repositories;
    using QLThuChi.Helpers;
    #endregion

    /// <summary>
    /// tuansl added: insert new khenthuong progress
    /// </summary>
    public partial class FrmLapPhieuChiVLXD : DevComponents.DotNetBar.Office2007Form
    {
        public EventHandler Handler { get; set; }
        private bool Updated = false;
        private EnumUpdateMode UpdateMode = EnumUpdateMode.INSERT;
        // Hidden files are used to store ids 
        private DevComponents.DotNetBar.Controls.TextBoxX txtMaCongTrinhGiaiDoan;
        private DevComponents.DotNetBar.Controls.TextBoxX txtMaPhieu;

        public FrmLapPhieuChiVLXD(int magiaidoan)
        {
            InitializeComponent();
            InitHiddenFields();

            txtMaCongTrinhGiaiDoan.Text = magiaidoan.ToString();
            var giaidoan = CongTrinh_GiaiDoanRepository.SelectByID(int.Parse(txtMaCongTrinhGiaiDoan.Text));
            txtCongTrinh.Text = giaidoan.CongTrinh.TenCongTrinh;
            txtGiaiDoan.Text = giaidoan.GiaiDoan.TenGiaiDoan;
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            UpdateMode = EnumUpdateMode.INSERT;
            EraseTextboxes();
            SetDefaultMode(false);
            DisableCmdButtons();
            txtNgayLapPhieu.Focus();
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            if (txtMaPhieu.Text != "")
            {
                UpdateMode = EnumUpdateMode.UPDATE;
                SetDefaultMode(false);
                DisableCmdButtons();
            }
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            if (lstvData.SelectedItems.Count > 0)
            {
                if (MessageBox.Show("Bạn có chắc chắn xóa dữ liệu này không?", "Xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (PhieuChi_VLXDRepository.Delete(int.Parse(txtMaPhieu.Text)))
                    {
                        Updated = true;
                        EraseTextboxes();
                        txtMaPhieu.Text = "";
                        LoadData();
                        MessageBox.Show("Xóa dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("Xóa dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void btnGhi_Click(object sender, EventArgs e)
        {
            string errorText = "";
            var success = false;

            if (!ValidateUserInput(ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (UpdateMode == EnumUpdateMode.INSERT)
            {
                if (ActionAdd())
                {
                    success = true;
                }
            }
            else if (UpdateMode == EnumUpdateMode.UPDATE)
            {
                if (ActionUpdate())
                {
                    success = true;
                }
            }
            // Inform result for nguoidung
            if (success)
            {
                LoadData();
                SetDefaultMode(true);
                Updated = true;
                MessageBox.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Cập nhật dữ liệu thất bại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnHuy_Click(object sender, EventArgs e)
        {
            // Case 1
            if (txtMaPhieu.Text != "")
                LoadCurrentQuaTrinhInfo(int.Parse(txtMaPhieu.Text));
            else
                EraseTextboxes();

            SetDefaultMode(true);
            btnThem.Focus();
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmNhapQuaTrinhKhenThuong_Load(object sender, EventArgs e)
        {
            LoadData();
            EraseTextboxes();
            SetDefaultMode(true);
            txtNgayLapPhieu.Text = String.Format("{0:dd/MM/yyyy}", DateTime.Now);
        }

        private void lstvData_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstvData.SelectedItems.Count > 0)
            {
                var phieu = (PhieuChi_VLXD)lstvData.SelectedItems[0].Tag;
                txtMaPhieu.Text = phieu.MaPhieu.ToString();
                LoadCurrentQuaTrinhInfo(phieu.MaPhieu);
                txtTongChiPhi.Text = String.Format("{0:#,##0;Nothing}", GetTongChiPhi());
                txtNgayLapPhieu.Text = String.Format("{0:dd/MM/yyyy}", phieu.NgayLapPhieu.Value);
            }
        }

        private void FrmNhapQuaTrinhKhenThuong_FormClosed(object sender, FormClosedEventArgs e)
        {
            
        }

        /// <summary>
        /// Load list of congtac progresses of specified nhanvien
        /// </summary>
        public void LoadData()
        {
            var lstItem = PhieuChi_VLXDRepository.SelectByMaCongTrinhGiaiDoan(int.Parse(txtMaCongTrinhGiaiDoan.Text));
            lstvData.Items.Clear();
            for (int i = 0; i < lstItem.Count; i++)
            {
                var objListViewItem = new ListViewItem();
                objListViewItem.Tag = lstItem[i];
                objListViewItem.Text = (i + 1).ToString();
                objListViewItem.SubItems.Add(String.Format("{0:dd/MM/yyyy}", lstItem[i].NgayLapPhieu.Value));
                lstvData.Items.Add(objListViewItem);
            }
        }

        /// <summary>
        /// Init hidden fields
        /// </summary>
        public void InitHiddenFields()
        {
            // Add a new textbox
            txtMaCongTrinhGiaiDoan = new DevComponents.DotNetBar.Controls.TextBoxX
            {
                Name = "txtMaCongTrinhGiaiDoan",
                Text = ""
            };
            txtMaCongTrinhGiaiDoan.Visible = false;

            // Add a new textbox
            txtMaPhieu = new DevComponents.DotNetBar.Controls.TextBoxX
            {
                Name = "txtMaPhieu",
                Text = ""
            };
            txtMaPhieu.Visible = false;
        }

        /// <summary>
        /// tuansl added: function is used to transfer data when event would be raised
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void TransferDataInfo(object sender, MyEvent e)
        {
            this.Handler(this, e);
        }

        /// <summary>
        /// Validate user inputs
        /// </summary>
        /// <returns></returns>
        public bool ValidateUserInput(ref string errorText)
        {
            if (lstDanhSachVLXD.Items.Count == 0)
            {
                errorText = "Danh sách hiện thời không có gì!";
                return false;
            }
            return true;
        }

        /// <summary>
        /// Add a new item to DB
        /// </summary>
        /// <returns></returns>
        private bool ActionAdd()
        {
            try
            {
                // Open connection
                DataContext.Instance.Connection.Open();
                // Define a transaction for the operations
                using (var transaction = DataContext.Instance.Connection.BeginTransaction())
                {
                    var newItem = new PhieuChi_VLXD
                    {
                        MaCongTrinhGiaiDoan = int.Parse(txtMaCongTrinhGiaiDoan.Text),
                        MaNguoiLapPhieu = GlobalVars.g_CurrentUser.MaNguoiDung,
                        NgayLapPhieu = DateTime.Now
                    };

                    if (!PhieuChi_VLXDRepository.Insert(newItem))
                    {
                        return false;
                    }

                    for (int i = 0; i < lstDanhSachVLXD.Items.Count; i++)
                    {
                        var chitiet = new ChiTietPhieu
                        {
                            MaPhieu = newItem.MaPhieu,
                            MaVLXD = int.Parse(lstDanhSachVLXD.Items[i].SubItems[0].Text),
                            SoLuong = int.Parse(lstDanhSachVLXD.Items[i].SubItems[3].Text),
                            DonGia = long.Parse(lstDanhSachVLXD.Items[i].SubItems[4].Text.Contains(",") ? lstDanhSachVLXD.Items[i].SubItems[4].Text.Replace(",", "") : lstDanhSachVLXD.Items[i].SubItems[4].Text.Replace(".", ""))
                        };
                        if (!ChiTietPhieuRepository.Insert(chitiet))
                        {
                            return false;
                        }
                    }

                    RefreshQuaTrinh(newItem.MaPhieu.ToString());

                    // Mark the transaction as complete
                    transaction.Commit();
                    DataContext.Instance.Connection.Close();
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Update an item in DB
        /// </summary>
        /// <returns></returns>
        private bool ActionUpdate()
        {
            try
            {
                // Open connection
                DataContext.Instance.Connection.Open();
                // Define a transaction for the operations
                using (var transaction = DataContext.Instance.Connection.BeginTransaction())
                {
                    var updateItem = PhieuChi_VLXDRepository.SelectByID(int.Parse(txtMaPhieu.Text));

                    // Removew old items
                    var lstItem = ChiTietPhieuRepository.SelectByMaPhieu(updateItem.MaPhieu);
                    foreach (var item in lstItem)
                    {
                        if (!ChiTietPhieuRepository.Delete(item.MaChiTietPhieu))
                        {
                            return false;
                        }
                    }

                    for (int i = 0; i < lstDanhSachVLXD.Items.Count; i++)
                    {
                        var chitiet = new ChiTietPhieu
                        {
                            MaPhieu = updateItem.MaPhieu,
                            MaVLXD = int.Parse(lstDanhSachVLXD.Items[i].SubItems[0].Text),
                            SoLuong = int.Parse(lstDanhSachVLXD.Items[i].SubItems[3].Text),
                            DonGia = long.Parse(lstDanhSachVLXD.Items[i].SubItems[4].Text.Contains(",") ? lstDanhSachVLXD.Items[i].SubItems[4].Text.Replace(",", "") : lstDanhSachVLXD.Items[i].SubItems[4].Text.Replace(".", ""))
                        };
                        if (!ChiTietPhieuRepository.Insert(chitiet))
                        {
                            return false;
                        }
                    }

                    // Mark the transaction as complete
                    transaction.Commit();
                    DataContext.Instance.Connection.Close();
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Load info of current quatrinh
        /// If mode is insert: update txtMaKhenThuong
        /// Else: not change
        /// </summary>
        public void LoadCurrentQuaTrinhInfo(int id)
        {
            var lstItem = ChiTietPhieuRepository.SelectByMaPhieu(id);
            lstDanhSachVLXD.Items.Clear();
            for(int i=0; i<lstItem.Count; i++)
            {
                var vlxd = VLXDRepository.SelectByID(lstItem[i].MaVLXD.Value);
                var objListViewItem = new ListViewItem();
                objListViewItem.Text = vlxd.MaVLXD.ToString();
                objListViewItem.SubItems.Add(vlxd.TenVLXD);
                objListViewItem.SubItems.Add(vlxd.MaDonViTinh == null ? "" : vlxd.DonViTinh.TenDonViTinh);
                objListViewItem.SubItems.Add(lstItem[i].SoLuong.ToString());
                objListViewItem.SubItems.Add(String.Format("{0:#,##0;Nothing}", lstItem[i].DonGia));
                lstDanhSachVLXD.Items.Add(objListViewItem);
            }
        }

        /// <summary>
        /// Disable them, xoa, sua
        /// </summary>
        public void DisableCmdButtons()
        {
            btnThem.Enabled = false;
            btnSua.Enabled = false;
            btnXoa.Enabled = false;
        }

        /// <summary>
        /// Store ma qua trinh cong tac
        /// </summary>
        /// <param name="val"></param>
        public void RefreshQuaTrinh(string val)
        {
            txtMaPhieu.Text = val;
        }

        /// <summary>
        /// Erase data in textboxes when mode is insert
        /// </summary>
        public void EraseTextboxes()
        {
            txtTongChiPhi.Text = "";
            lstDanhSachVLXD.Items.Clear();
        }

        /// <summary>
        /// Set default status
        /// </summary>
        /// <param name="val">default is true</param>
        public void SetDefaultMode(bool val = true)
        {
            btnThemVaoDanhSach.Enabled = !val;
            btnXoaKhoiDanhSach.Enabled = !val;

            btnThem.Enabled = val;
            btnSua.Enabled = val;
            btnXoa.Enabled = val;
            btnGhi.Enabled = !val;
            btnHuy.Enabled = !val;
        }

        private void txtNam_KeyPress(object sender, KeyPressEventArgs e)
        {
            // Only allow type number
            if (!char.IsNumber(e.KeyChar) && (Keys)e.KeyChar != Keys.Back)
            {
                e.Handled = true;
            }
        }

        private void FrmNhapQuaTrinhKhenThuong_Shown(object sender, EventArgs e)
        {
        }

        private void btnThemVaoDanhSach_Click(object sender, EventArgs e)
        {
            FrmChonVLXD frm = new FrmChonVLXD();
            frm.Handler += ThemVaoDanhSach;
            frm.ShowDialog();
        }

        public void ThemVaoDanhSach(object sender, EventArgs e)
        {
            var eventType = (MyEvent)e;
            string[] comp = eventType.Data.Split(new char[] { '#' });

            var vlxd = VLXDRepository.SelectByID(int.Parse(comp[0]));
            
            var objListViewItem = new ListViewItem();
            objListViewItem.Text = comp[0];
            objListViewItem.SubItems.Add(vlxd.TenVLXD);
            objListViewItem.SubItems.Add(vlxd.MaDonViTinh == null ? "" : vlxd.DonViTinh.TenDonViTinh);
            objListViewItem.SubItems.Add(comp[1]);
            objListViewItem.SubItems.Add(comp[2]);
            lstDanhSachVLXD.Items.Add(objListViewItem);

            txtTongChiPhi.Text = String.Format("{0:#,##0;Nothing}", GetTongChiPhi());
        }

        public long GetTongChiPhi()
        {
            long tongtien = 0;
            for (int i = 0; i < lstDanhSachVLXD.Items.Count; i++)
            {
                tongtien += (int.Parse(lstDanhSachVLXD.Items[i].SubItems[3].Text) * long.Parse(lstDanhSachVLXD.Items[i].SubItems[4].Text.Contains(",") ? lstDanhSachVLXD.Items[i].SubItems[4].Text.Replace(",", "") : lstDanhSachVLXD.Items[i].SubItems[4].Text.Replace(".", "")));
            }
            return tongtien;
        }

        private void btnXoaKhoiDanhSach_Click(object sender, EventArgs e)
        {
            if (lstDanhSachVLXD.SelectedItems.Count > 0)
            {
                lstDanhSachVLXD.Items.RemoveAt(lstDanhSachVLXD.SelectedIndices[0]);
            }
        }
    }
}